from flask_restful import Resource, reqparse, marshal_with
from sqlalchemy import and_

from apps.common.result import Result
from apps.main.models import Movies
from apps.movies.fields import result

"""
对返回值的处理
对参数的处理
tag 0 表示首页
     1 表示全部
     
     :arg 传递参数的key
    :type int str float
    :help 错误的提示信息
    :default 若没有参数则用默认的
    :required 必要
    :action   append(追加)
    :location 位置参数
"""
# http://127.0.0.1:8000/movies?

class MovieListApi(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('tag',type=int,default=1)
        self.parser.add_argument('page', type=int, default=1)
        self.parser.add_argument('size', type=int, default=3)

    @marshal_with(result)
    def get(self):
        args = self.parser.parse_args()
        tag = args.get('tag')
        page = args.get('page')
        size = args.get('size')

        hot_query = Movies.query.filter(and_(Movies.is_delete == 0,Movies.flag == 1))
        will_query = Movies.query.filter(and_(Movies.is_delete == 0,Movies.flag == 2 ))

        # 分页
        # hot_movies = hot_query.paginate(page=page, per_page=size, error_out=False).items
        # will_movies = will_query.paginate(page=page, per_page=size, error_out=False).items

        if tag:
            """表示获取全部数据 (热门,即将)"""
            hot_count = hot_query.count()
            will_count = will_query.count()
            hot_movies = hot_query.paginate(page=page, per_page=size, error_out=False).items
            will_movies = will_query.paginate(page=page, per_page=size, error_out=False).items

            # hot_movies = hot_query.all()
            # will_movies = will_query.all()

        else:
            """表示首页数据 (热门总数,即将总数热门前5,即将前5)"""
            hot_count = hot_query.count()
            will_count = will_query.count()
            hot_movies = hot_query.limit(5).offset(0).all()
            will_movies = will_query.limit(5).offset(0).all()

        data = {
            'movie': {
                'hot_count': hot_count,
                'will_count': will_count,
                'hot_movies': hot_movies,
                'will_movies': will_movies,
                'page':page
            }
        }

        return Result.get_success_result_obj(data)

